package com.jianbo.proxy.core;

import java.util.Map;

import org.smartboot.http.server.HttpRequest;

import com.jianbo.proxy.conf.ArgsConf;
import com.jianbo.proxy.conf.jsconfig.FilterConfig;
import com.jianbo.proxy.entity.HttpResponseMiddle;
import com.jianbo.proxy.service.FilterWebService;
import com.jianbo.proxy.util.ByteUtil;
import com.jianbo.proxy.util.FileUtil;
import com.jianbo.proxy.util.JsUtil;
import com.jianbo.proxy.util.RegUtil;
import com.jianbo.proxy.util.ThreadDataUtil;

public class FilterWeb implements Web {

    @Override
    public boolean handle(String path, HttpRequest request, HttpResponseMiddle response) throws Exception {

        Map<String, String> conf = filterConfig.getFilterMap();
        for(String mappingReg : conf.keySet()) {
            boolean find = RegUtil.find(path, mappingReg);
            // if(find == false) {
            //     find = mappingReg.equals(path);
            // }
            // Debug.info(mappingReg + "[]" + path + "[]" + find);
            ArgsConf argsConfig = ArgsConf.getInstance();
            String filterFile = argsConfig.getConfDir() + conf.get(mappingReg);
            if(find) {
                if(FileUtil.exist(filterFile)) {
                    String jsCode = FileUtil.readString(filterFile);
                    // 加载js文件，获得js文件输出，下入到 response 中
                    jsCode = FilterWebService.jsCode(jsCode);
                    byte[] bytes = response.read();
                    String oldCode = ByteUtil.toStr(bytes);

                    // 通过 ThreadDataUtil 进行数据交互，减少js执行
                    ThreadDataUtil.put("code", oldCode);
                    ThreadDataUtil.put("url", path);

                    if(path.endsWith(".html")) {
                        JsUtil.runFull(jsCode);
                    } else {
                        // JsUtil.run(jsCode, "console", "require");
                        JsUtil.runFull(jsCode);
                    }

                    String result = ThreadDataUtil.get("code");
                    
                    ThreadDataUtil.clear();
                    
                    response.write(ByteUtil.bytes(result));

                }
            }
        }
        return false;
    }

    FilterConfig filterConfig;
    public void setFilterConf(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
    
}
